<template>
  <!------------------------------------ 地址列表页面 ------------------------------------
    @desc 地址列表，修改/新增列表弹窗
    @author kyle
    @date 2021-03-05
    @method
      colseAdress    ———— 关闭地址选择页面
      changeAddress  ———— 修改页面收货地址
  -->
  <div>
    <van-nav-bar
      fixed
      title="选择地址"
      left-arrow
      @click-left="colseAdress"
    />
    <div class="has-top has-bottom">
      <!-- <top-search
        type="primary"
        :val="val"
        :area-show="areaShow"
        :input-style="inputStyle"
        :placeholder="placeholder"
        @search="search"
      /> -->
      <ul class="ads-list fs-28">
        <!-- ****************获取微信收货地址*************** -->
        <!--<li v-show="$utils.wechat().isWechat" class="ads-item">
          <p class="flex-s-c " @click="getWxAdress()">
            <svg-icon icon-class="wechat" class="fs-40 mr-25 is-40" />
            <span class="flex-1">获取微信收货地址</span>
            <span class="arrow" />
          </p>
        </li>-->
				<div v-for="(item,index) in addressList" :key="index">	
					<van-swipe-cell>
					<li class="ads-item h-184" @click="changeAddress(item,index)">
					
						<div class="flex-s-c ">
							<div class="ads-item-left flex-s-0 " :class="item.Selected?'ads-item-selected':''" />
							<div class=" flex-1">
								<p>
									<span v-show="item.IsDefault" class="ads-default bg-primary color-white">默认</span>
									<span class="mr-15">{{ item.ContactName }}</span>
									<span>{{ item.ContactTel }}</span>
								</p>
								<p class="mt-10 fs-24">{{ item.ProvinceName }}{{ item.CityName }}{{ item.AreaName }}{{ item.StreetName }}{{ item.ContactAddress }}</p>
							</div>
							<svg-icon icon-class="edit" class="fs-32 color-gray-light ml-100  flex-s-0" @goPage="edit(item,index)" />
						</div>
						
					</li>
					<template #right >
						<van-button square class="h-184" color="#2A2D33" text="设为默认" @click="setDefaultAddress(item.ID)" />
						<van-button square class="h-184"  color="#E01212" text="删除" @click="deleteAddresss(item.ID)" />
					</template>
				</van-swipe-cell>
			</div>					
      </ul>
      <div class="fixed-bottom  bottom-box">
        <button class="btn-large color-white bg-primary" @click="edit()">新增地址</button>
      </div>
      <!-- 编辑/新增地址弹窗 -->
      <van-popup v-model="editData.show" position="bottom" style="height:100vh;">
        <addressEdit :address-data="editData.data" :userId="userId" :addressId="addressId" :adress-index="editData.index" @closeEdit="editData.show=false" @useAddress="useAddress" @deleteAddress="deleteAddress" />
      </van-popup>
    </div>

  </div>
</template>

<script>
import TopSearch from 'components/Search'
import addressEdit from 'components/address/edit'
import { GetUserAddressList, BatchSmartParse, UserAddressAddOrEdit, UserAddressDelete, UserAddressSetDefault } from 'api/member'
// GetReceivingAddressList 换 GetUserAddressList
export default {
  name: 'AddressList',
  components: {
    TopSearch,
    addressEdit

  },
  props: {
    userId: {
			type: Number,
			default: 0,
		}
  },
  data() {
    return {
      // 搜索栏配置及数据
      areaShow: false,
      val: '',
      inputStyle: 'inputStyle-2',
      placeholder: '搜索已有地址',

      addressList: {},
      editData: {
        data: {},
        index: -1,
        show: false
      },
			addressId: 0,
      selectaddress: 0,
    }
  },
  watch: {

  },
  created() {
    this.GetUserAddressList()
  },
  methods: {
    colseAdress() {
      this.$emit('colseAdress')
    },
    search(key) {
      this.GetUserAddressList(key)
    },
    getWxAdress() {
      const _this = this
      _this.$utils.getWxAdress(function(res) {
        console.log(res)
        const _arr = []
        const _addressObj = {
          ContactName: res.userName,
          ContactTel: res.telNumber,
          ContactAddress: res.provinceName + res.cityName + res.countryName + res.detailInfo
        }
        _arr.push(_addressObj)
        const _obj = {
          list: _arr
        }
        _this.BatchSmartParse(_obj)
      })
    },
    changeAddress(address, index) {
      this.addressList.forEach((item, ind) => {
        if (index === ind) {
          console.log(index)
          console.log(ind)
          item.Selected = true
        } else {
          item.Selected = false
        }
      })
      this.$forceUpdate()
      this.$emit('changeAddress', address)
			this.$emit('colseAdress')
    },
    edit(item = {}, index = -1) {
			if(item.ID){				
				this.addressId = item.ID
			}
      this.editData.data = item
      this.editData.index = index
      this.editData.show = true
    },

    useAddress(address, index) {
      this.editData.show = false
      let _index = index
      if (address.IsDefault === true) {
        this.addressList.forEach(item => {
          item.IsDefault = false
        })
      }
      if (index === -1) {
        _index = this.addressList.length
        this.addressList.push(address)
      } else {
        this.addressList[index] = address
      }
      this.changeAddress(address, _index)
    },
    deleteAddress(index) {
      this.editData.show = false
      this.addressList.splice(index, 1)
      this.$forceUpdate()
    },
		// 删除地址
		deleteAddresss(id) {
			console.log(id,"删除")
      this.$dialog.confirm({
        message: '确定要删除该地址？'
      })
        .then(() => {
          // 调用删除地址接口
          this.UserAddressDelete(id)
        })
        .catch(() => {
          // on cancel
        })
    },
		UserAddressDelete(ids) {
      UserAddressDelete({ ids }).then(res => {
        if (res) {
          this.$toast.success('删除成功')
					this.GetUserAddressList()
        }
      })
    },
		//设为默认地址
		setDefaultAddress(id){
			UserAddressSetDefault({id:id}).then(res => {
				if(res){
					this.GetUserAddressList()
				}
			})
		},
    // 获取收货地址
    GetUserAddressList(searchKey = '') {
      let param = {
        searchKey:'',
      }
      if(this.userId){
        param.userId = this.userId
      }
      GetUserAddressList(param).then(res => {
        if (res) {
          console.log(res)
          this.addressList = res.Data
          this.addressList.forEach(item => {
            item.Selected = item.IsDefault
          })
        }
      })
    },
    // 识别地址
    BatchSmartParse(data) {
      BatchSmartParse(data).then(res => {
        if (res) {
          console.log(res)
          if (res.Data.successCount === 0) {
            this.$toast.fail('未能识别成功')
            return
          }
          let isExit = false
          const _targetAdress = res.Data.list[0]
          if (this.addressList && this.addressList.length > 0) {
            const _list = this.addressList
            for (let i = 0; i < _list.length; i++) {
              const _address = _list[i]
              if (_address.ContactName === _targetAdress.ContactName && _address.ContactTel === _targetAdress.ContactTel && _address.ContactAddress === _targetAdress.ContactAddress) {
                isExit = true
                this.changeAddress(_address, i)
                return
              }
            }
            if (!isExit) {
              this.UserAddressAddOrEdit(_targetAdress)
            }
          }
        }
      })
    },
    // 新增、编辑地址
    UserAddressAddOrEdit(obj) {
      UserAddressAddOrEdit(obj).then(res => {
        if (res) {
          console.log(res)
          this.useAddress(obj, -1)
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.ads-list{
  margin: 0 24px;
  .ads-item{
    background: $colorF;
    padding:30px 20px;
    border-radius: 12px;
    margin-top: 18px;
    .arrow{
      width: 20px;
      height: 20px;
      position: relative;
      &:after {
        top: 0;
        left: 0;
      }
    }
    .ads-item-left{
      width: 40px;
      height: 40px;
      border: 1px solid $colorC;
      border-radius: 100%;
      margin-right: 25px;
    }
    .ads-item-selected{
      background: $color3;
      border-color: $color3;
      position: relative;
      &:after{
        content:'';
        position: absolute;
        top: 6px;
        left: 6px;
        width: 16px;
        height: 8px;
        border: 4px solid;
        border-color: transparent transparent $colorF $colorF;
        transform: rotate(-45deg);
      }
    }
    .ads-default{
      display: inline-block;
      font-size: 24px;
      line-height: 34px;
      padding:0 10px;
      border-radius: 17px;
      margin-right: 12px;
    }
  }
}
.bottom-box{
  padding: 0 30px 44px 30px;
  display:flex;
  align-items: center;
  background: $colorF5;
}
.h-184{
	height: 184px;
}

</style>

